/*
 * @Author: rainbow
 * @Date: 2021-09-Sa 08:09:56
 * @Last Modified by:   rainbow
 * @Last Modified time: 2021-09-Sa 08:09:56
 */

const O   = require('../../utils/O');
const Db  = require('../../utils/Db');
const UserSql = require('../sql/userSql');
const userService = require('../service/userService');
// const { getConn } = require('../cluster')
const { getConn } = require('../index')
const Api = require('../../utils/Api')

const userApi = {
  // getById : async (id) => {
  //   const conn = await getConn()
  //   const res  = await Api.getById(conn, UserSql, id)
  //   // ...
  //   return Api.ret(res, conn)
  // },
  getById : async (id) => {
    return userService.getById(id)
  },
  queryCount: async (page, size) => {
    const conn = await getConn()
    const res  = await Api.queryCount(conn,UserSql, []
      ,'id,name,nick,email,phone','', 'order by id desc' + Db.getLimit(page, size))
    // ...
    return Api.ret(res, conn)
  },
  query: async (page, size) => {
    const conn = await getConn()
    const res  = await Api.query(conn,UserSql,[]
      , 'id,name,nick,email,phone','', 'order by id desc' + Db.getLimit(page, size))

    // ...
    return Api.ret(res, conn)
  },
  add: async function (user) {
    const conn = await getConn(true)
    let id
    try{
      this._checkName(conn,{name:user.name})
      id = await Api.add(conn,UserSql,user)
      // ...
      await conn.commit()
    }catch(e){
      await conn.rollback()
      throw e
    }finally{
      conn.release();
    }
    return id
  },
  updById: async (user) => {
    const conn = await getConn()
    // check name if update name
    if (user.name && user.id) {
      await this._checkName(conn, user)
    }
    const res = await Api.updById(conn,UserSql,user)
    // ...
    return Api.ret(res,conn)
  },
  upd: async function (setObj,whereObj) {
    const conn = await getConn()
    // check name if update name
    if (setObj.name && whereObj.id){
      await this._checkName(conn, { name: setObj.name, id: whereObj.id })
    }
    const res = await Api.upd(conn,UserSql,setObj,whereObj)
    // ...
    return Api.ret(res,conn)
  },

  delById: async (id) => {
    const conn = await getConn()
    const res  = await Api.delById(conn,UserSql,id)
    // ...
    return Api.ret(res,conn)
  },
  del: async (user) => {
    const conn = await getConn()
    const res  = await Api.del(conn,UserSql,user)
    // ...
    return Api.ret(res,conn)
  },
  /**
   * check name if used by other
   * @param  <conn></conn>
   * @param  <user>{name:string,id?:number}</user>
   * @return void
   */
  _checkName: async(conn,user) => {
    const sql = UserSql.isNameExist(user)
    const isNameUsedByOther = await conn.execute(sql.sql, sql.value)
    // console.log('ret ', isNameUsedByOther);
    const row = Db.getRowWithIdOrFalse(isNameUsedByOther)
    O.isTrue(row, 'name has exist')
  }
}

module.exports = userApi